package com.microservice.wechat.scheduler;

import com.microservice.common.utils.RedisUtil;
import com.microservice.wechat.service.WechatTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 微信Token定时刷新任务
 * 使用分布式锁保证多实例环境下只有一个实例执行
 */
@Component
@EnableScheduling
@Slf4j
public class WechatTokenScheduler {
    
    @Autowired
    private WechatTokenService tokenService;
    
    @Autowired
    private RedisUtil redisUtil;
    
    private static final String SCHEDULE_LOCK = "wechat:schedule:refresh:lock";
    
    /**
     * 每小时批量刷新一次所有Token（预热机制）
     * 避免高峰期调用微信API
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void refreshAllTokens() {
        // 使用分布式锁，保证只有一个实例执行
        boolean locked = redisUtil.set(SCHEDULE_LOCK, "1", 300);
        
        if (!locked) {
            log.info("其他实例正在批量刷新Token，本次跳过");
            return;
        }
        
        try {
            log.info("开始定时批量刷新Token");
            tokenService.refreshAllTokens();
            log.info("定时批量刷新Token完成");
        } catch (Exception e) {
            log.error("定时批量刷新Token失败", e);
        } finally {
            redisUtil.del(SCHEDULE_LOCK);
        }
    }
}
